import Vue from 'vue'
import VueRouter from 'vue-router'
import LoginView from '../views/LoginView.vue'

Vue.use(VueRouter)

const routes = [
  {
    path: '/login',
    name: 'login',
    component: LoginView
  },
  {
    path: '/',
    component: () => import(/* webpackChunkName: "layout" */ '../views/LayoutView.vue'),
    children: [
      {
        path: '',
        name: 'home',
        component: () => import(/* webpackChunkName: "home" */ '../views/HomeView.vue')
      },
      {
        path: 'auth',
        name: 'auth',
        component: () => import(/* webpackChunkName: "auth" */ '../views/AuthView.vue')
      },
      {
        path: 'menu',
        name: 'menu',
        component: () => import(/* webpackChunkName: "menu" */ '../views/MenuView.vue')
      }
    ]
  }
]
const router = new VueRouter({
  routes
})

router.beforeEach((to, from, next) => {
  // 判断用户有没有登录
  const isLogin = localStorage.getItem('isLogin')
  console.log(to)
  // 如果登录了，就直接下一步
  if (!isLogin) {
    if (to.name === 'login') {
      next()
    } else {
      next('/login')
    }
  } else {
    if (to.name === 'login') {
      next('/')
    } else {
      next()
    }
  }
  // 如果没有登录，访问的是login，那就next()
  // 如果没有登录，访问的不是login，那就next('/login')
  // 如果登录了，访问的是login，直接next('/')
  // 如果登录了，访问的是非login，直接next()
})

export default router
